# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
import objc
from GlyphsApp import *
from GlyphsApp.plugins import *
import math


class Tradingaddhorizontal(FilterWithoutDialog):
    @objc.python_method
    def settings(self):
        self.menuName = Glyphs.localize({'zh': '贸易冲击体一键添加横线'})


    @objc.python_method
    def cross_point(self,line1, line2):  # 计算交点函数
        if line1[0] == line1[2]:
            line3 = line2
            line4 = line1
        else:
            line3 = line1
            line4 = line2
        x1 = line3[0]  # 取四点坐标
        y1 = line3[1]
        x2 = line3[2]
        y2 = line3[3]

        x3 = line4[0]
        y3 = line4[1]
        x4 = line4[2]
        y4 = line4[3]
        k1 = (y2 - y1) * 1.0 / (x2 - x1)  # 计算k1,由于点均为整数，需要进行浮点数转化

        b1 = y1 * 1.0 - x1 * k1 * 1.0  # 整型转浮点型是关键
        if (x4 - x3) == 0:  # L2直线斜率不存在操作
            k2 = None
            b2 = 0
        else:
            k2 = (y4 - y3) * 1.0 / (x4 - x3)  # 斜率存在操作
            b2 = y3 * 1.0 - x3 * k2 * 1.0
        if k2 == None:
            x = x3
        else:
            x = (b2 - b1) * 1.0 / (k1 - k2)
        y = k1 * x * 1.0 + b1 * 1.0
        return [x, y]

    @objc.python_method
    def is_counter_clockwise(self,points):
        """检查多边形是否为逆时针方向"""
        area = 0
        n = len(points)
        for i in range(n):
            x1, y1 = points[i]
            x2, y2 = points[(i + 1) % n]
            area += (x1 * y2 - x2 * y1)
        return area > 0

    @objc.python_method
    def get_external_normal(self,polygon, edge_start, edge_end):
        """
        获取指向多边形外部的法向量

        参数:
            polygon: 多边形所有顶点列表
            edge_start: 边起点
            edge_end: 边终点

        返回:
            (dx, dy) 表示外部方向的单位向量
        """
        # 计算边向量
        edge_vec = [edge_end.x - edge_start.x, edge_end.y - edge_start.y]

        # 计算法向量 (两个可能方向)
        normal1 = [edge_vec[1], -edge_vec[0]]
        normal2 = [-edge_vec[1], edge_vec[0]]

        # 归一化法向量
        length = math.sqrt(normal1[0] ** 2 + normal1[1] ** 2)
        if length > 0:
            normal1 = [normal1[0] / length, normal1[1] / length]
            normal2 = [normal2[0] / length, normal2[1] / length]

        # 检查多边形方向
        ccw = self.is_counter_clockwise([(pt.x, pt.y) for pt in polygon])

        # 找到指向外部的法向量
        # 计算边的中点
        mid_x = (edge_start.x + edge_end.x) / 2
        mid_y = (edge_start.y + edge_end.y) / 2

        # 测试点1: 沿normal1方向稍微移动
        test_point1 = (mid_x + normal1[0] * 0.1, mid_y + normal1[1] * 0.1)

        # 测试点2: 沿normal2方向稍微移动
        test_point2 = (mid_x + normal2[0] * 0.1, mid_y + normal2[1] * 0.1)

        # 使用射线法判断测试点是否在多边形外部
        if self.is_point_outside_polygon(test_point1, polygon) and not self.is_point_outside_polygon(test_point2, polygon):
            return normal1
        elif self.is_point_outside_polygon(test_point2, polygon) and not self.is_point_outside_polygon(test_point1, polygon):
            return normal2

        # 如果无法确定，根据多边形方向选择
        return normal1 if ccw else normal2

    @objc.python_method
    def is_point_outside_polygon(self,point, polygon):
        """
        使用射线法判断点是否在多边形外部

        参数:
            point: 要测试的点 (x, y)
            polygon: 多边形顶点列表 [Node]

        返回:
            True 如果点在多边形外部，否则 False
        """
        x, y = point
        n = len(polygon)
        inside = False

        p1x, p1y = polygon[0].x, polygon[0].y
        for i in range(n + 1):
            p2x, p2y = polygon[i % n].x, polygon[i % n].y
            if y > min(p1y, p2y):
                if y <= max(p1y, p2y):
                    if x <= max(p1x, p2x):
                        if p1y != p2y:
                            xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
                        if p1x == p2x or x <= xinters:
                            inside = not inside
            p1x, p1y = p2x, p2y

        return not inside

    @objc.python_method
    def filter(self, Layer,inEditView, customParameters):
        # 主程序
        selected_nodes = []
        selected_path = None
        # 找到选中的边和所在路径
        for path in Layer.paths:
            for i, node in enumerate(path.nodes):
                if node.selected:
                    selected_nodes.append(node)
                    selected_path = path  # 保存路径引用

        # 确保选中两个节点构成一条边
        if len(selected_nodes) == 3:
            print("请选择一条边（两个节点）")
            print("selected_path:", selected_path)
            selected_nodes_sorted = []
            if selected_nodes[2].index == len(selected_path) - 1 and selected_nodes[0].index == 0 and selected_nodes[
                1].index == 1:
                selected_nodes_sorted.append(selected_nodes[2])
                selected_nodes_sorted.append(selected_nodes[0])
                selected_nodes_sorted.append(selected_nodes[1])
            elif selected_nodes[2].index == len(selected_path) - 1 and selected_nodes[0].index == 0 and selected_nodes[
                1].index == len(selected_path) - 2:
                selected_nodes_sorted.append(selected_nodes[1])
                selected_nodes_sorted.append(selected_nodes[2])
                selected_nodes_sorted.append(selected_nodes[0])
            else:
                selected_nodes_sorted.append(selected_nodes[0])
                selected_nodes_sorted.append(selected_nodes[1])
                selected_nodes_sorted.append(selected_nodes[2])
            print("selected_nodes_sortedselected_nodes_sorted:", selected_nodes_sorted)
            # 获取整个多边形顶点
            polygon = selected_path.nodes

            # 获取指向外部的法向量
            normal1 = self.get_external_normal(polygon, selected_nodes[0], selected_nodes[1])
            print("外部法向量1:", normal1)
            normal2 = self.get_external_normal(polygon, selected_nodes[1], selected_nodes[2])
            print("外部法向量1:", normal2)
            # 移动距离
            offset1 = 25
            offset2 = 50
            # 计算移动后的新位置
            new_x0 = selected_nodes_sorted[0].x + normal1[0] * offset1
            new_y0 = selected_nodes_sorted[0].y + normal1[1] * offset1
            new_x1 = selected_nodes_sorted[1].x + normal1[0] * offset1
            new_y1 = selected_nodes_sorted[1].y + normal1[1] * offset1
            line1 = [new_x0, new_y0, new_x1, new_y1]
            new_x2 = selected_nodes_sorted[1].x + normal2[0] * offset1
            new_y2 = selected_nodes_sorted[1].y + normal2[1] * offset1
            new_x3 = selected_nodes_sorted[2].x + normal2[0] * offset1
            new_y3 = selected_nodes_sorted[2].y + normal2[1] * offset1
            line2 = [new_x2, new_y2, new_x3, new_y3]
            position1 = self.cross_point(line1, line2)

            new_x4 = selected_nodes_sorted[0].x + normal1[0] * offset2
            new_y4 = selected_nodes_sorted[0].y + normal1[1] * offset2
            new_x5 = selected_nodes_sorted[1].x + normal1[0] * offset2
            new_y5 = selected_nodes_sorted[1].y + normal1[1] * offset2

            line3 = [new_x4, new_y4, new_x5, new_y5]
            new_x6 = selected_nodes_sorted[1].x + normal2[0] * offset2
            new_y6 = selected_nodes_sorted[1].y + normal2[1] * offset2
            new_x7 = selected_nodes_sorted[2].x + normal2[0] * offset2
            new_y7 = selected_nodes_sorted[2].y + normal2[1] * offset2

            line4 = [new_x6, new_y6, new_x7, new_y7]
            position2 = self.cross_point(line3, line4)
            node1 = (new_x0, new_y0)
            node2 = (position1[0], position1[1])
            node3 = (new_x3, new_y3)
            node4 = (new_x7, new_y7)
            node5 = (position2[0], position2[1])
            node6 = (new_x4, new_y4)

            newPath = GSPath()
            newNode1 = GSNode(node1)
            newNode2 = GSNode(node2)
            newNode3 = GSNode(node3)
            newNode4 = GSNode(node4)
            newNode5 = GSNode(node5)
            newNode6 = GSNode(node6)
            newnodes_list = [newNode1, newNode2, newNode3, newNode4, newNode5, newNode6]
            for new_node in newnodes_list:
                newPath.nodes.append(new_node)
            newPath.closed = True
            Layer.paths.append(newPath)

        if len(selected_nodes) == 2:
            print("选中的节点:", selected_nodes)

            # 获取整个多边形顶点
            polygon = selected_path.nodes

            # 获取指向外部的法向量
            normal = self.get_external_normal(polygon, selected_nodes[0], selected_nodes[1])
            print("外部法向量:", normal)

            # 移动距离
            offset1 = 25
            offset2 = 50

            # 计算移动后的新位置
            new_x0 = selected_nodes[0].x + normal[0] * offset1
            new_y0 = selected_nodes[0].y + normal[1] * offset1
            new_x1 = selected_nodes[1].x + normal[0] * offset1
            new_y1 = selected_nodes[1].y + normal[1] * offset1

            new_x2 = selected_nodes[0].x + normal[0] * offset2
            new_y2 = selected_nodes[0].y + normal[1] * offset2
            new_x3 = selected_nodes[1].x + normal[0] * offset2
            new_y3 = selected_nodes[1].y + normal[1] * offset2
            node1 = (new_x0, new_y0)
            node2 = (new_x1, new_y1)
            node3 = (new_x2, new_y2)
            node4 = (new_x3, new_y3)
            print(node1, node2, node3, node4)

            newPath = GSPath()
            newNode1 = GSNode(node1)
            newNode2 = GSNode(node3)
            newNode3 = GSNode(node4)
            newNode4 = GSNode(node2)
            newnodes_list = [newNode1, newNode2, newNode3, newNode4]
            for new_node in newnodes_list:
                newPath.nodes.append(new_node)
            newPath.closed = True
            Layer.paths.append(newPath)

    @objc.python_method
    def __file__(self):
        """Please leave this method unchanged"""
        return __file__